package com.qyhl.webtv.commonlib.base;

import android.Manifest;
import android.app.Application;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.util.Log;

import com.alibaba.sdk.android.push.CloudPushService;
import com.alibaba.sdk.android.push.CommonCallback;
import com.alibaba.sdk.android.push.huawei.HuaWeiRegister;
import com.alibaba.sdk.android.push.noonesdk.PushServiceFactory;
import com.alibaba.sdk.android.push.register.MiPushRegister;
import com.alibaba.sdk.android.push.register.OppoRegister;
import com.alibaba.sdk.android.push.register.VivoRegister;
import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVInstallation;
import com.avos.avoscloud.AVOSCloud;
import com.avos.avoscloud.PushService;
import com.avos.avoscloud.SaveCallback;
import com.avos.avoscloud.im.v2.AVIMClient;
import com.example.sdk.statisticssdk.StatisticsMainInit;
import com.qyhl.webtv.basiclib.base.BaseApplication;
import com.qyhl.webtv.basiclib.utils.MPermissionUtils;
import com.qyhl.webtv.basiclib.utils.NetUtil;
import com.qyhl.webtv.basiclib.utils.network.EasyHttp;
import com.qyhl.webtv.basiclib.utils.network.cache.converter.SerializableDiskConverter;
import com.qyhl.webtv.basiclib.utils.network.cache.model.CacheMode;
import com.qyhl.webtv.commonlib.R;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.constant.AppConfigConstant;
import com.qyhl.webtv.commonlib.entity.VersionBean;
import com.qyhl.webtv.commonlib.entity.config.MessageDetailBean;
import com.qyhl.webtv.commonlib.entity.news.NewsStyleBean;
import com.qyhl.webtv.commonlib.utils.CustomUserProvider;
import com.qyhl.webtv.commonlib.utils.DeviceUtils;
import com.qyhl.webtv.commonlib.utils.cache.SpfManager;
import com.qyhl.webtv.commonlib.utils.config.AppConfigUtil;
import com.qyhl.webtv.commonlib.utils.push.PushTools;
import com.tencent.bugly.Bugly;
import com.umeng.commonsdk.UMConfigure;
import com.umeng.socialize.PlatformConfig;

import java.util.ArrayList;
import java.util.List;

import cn.leancloud.chatkit.LCChatKit;

/**
 * 通用配置初始化
 *
 * @author helin
 * @date 2019年2月28日17:51:57
 */
public class ComminApplication extends BaseApplication {
    private static final String TAG = "Init";
    public static ComminApplication app;

    public static ComminApplication getApp() {
        return app;
    }


    @Override
    public void initModuleApp(Application application) {
        app = this;
    }

    private void initLeanCloud(Application application) {

        //初始化聊天组件
        LCChatKit.getInstance().setProfileProvider(CustomUserProvider.getInstance());
        LCChatKit.getInstance().init(application, CommonUtils.getInstance().getLeanCloudAppid(), CommonUtils.getInstance().getLeanCloudAppkey());
        //调试模式，正式发布请关闭
        AVOSCloud.setDebugLogEnabled(false);
        AVIMClient.setAutoOpen(true);
        PushService.setAutoWakeUp(true);

        AVInstallation.getCurrentInstallation().saveInBackground(new SaveCallback() {
            @Override
            public void done(AVException e) {
                if (e == null) {
                    // 保存成功
                    String installationId = AVInstallation.getCurrentInstallation().getInstallationId();
                } else {
                    // 保存失败，输出错误信息
                }
            }
        });

    }

//    /**
//     * 广告
//     */
//    private void initPtgAd() {
//        PtgSDKConfig config = new PtgSDKConfig.Builder()
//                .setAppName(CommonUtils.getInstance().getAppName())//App名称
//                .setMediaId(CommonUtils.getInstance().getPtgId())//ptg后台应用ID
//                .setMediaSecret(CommonUtils.getInstance().getPtgSecret())//ptg后台应用密钥
//                .setDebug(true)//是否开启日志
//                .build();
//
//        PtgAdSdk.init(app, config,
//                new TTProvider(),
//                new PtgApiProvider(),
//                new GdtProvider()
//        ); // 初始化 SDK, 初始化参数需要 根据依赖进行添加
//
//
//    }

    /**
     * 四川融媒统计
     */
    private void initStatistics() {
        String areaId = "";//区县号
        if (CommonUtils.getInstance().getSite() == 148) {
            areaId = "1321";
        }

        if (CommonUtils.getInstance().getSite() == 145) {
            areaId = "0322";
        }

        String versionName;
        //获取当前版本号
        try {
            PackageManager manager = app.getPackageManager();
            PackageInfo info = manager.getPackageInfo(app.getPackageName(), 0);
            versionName = info.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            versionName = "";
        }

        String deviceId;
        if (MPermissionUtils.checkPermissions(app, Manifest.permission.READ_PHONE_STATE)) {
            deviceId = DeviceUtils.getDeviceId(this);
        } else {
            deviceId = "";
        }

        String ipAddress;
        if (MPermissionUtils.checkPermissions(app, Manifest.permission.INTERNET)) {
            ipAddress = NetUtil.getIPAddress(true);
        } else {
            ipAddress = "";
        }

        StatisticsMainInit.SDKInit(areaId, deviceId, versionName, ipAddress, NetUtil.getNetWorkTypeName(app));

    }

    /**
     * 初始化网络框架
     */
    public void initHttp(String baseUrl) {
        //以下设置的所有参数是全局参数,同样的参数可以在请求的时候再设置一遍,那么对于该请求来讲,请求中的参数会覆盖全局参数
        EasyHttp.getInstance()
                //可以全局统一设置全局URL.//设置全局URL  url只能是域名 或者域名+端口号
                .setBaseUrl(baseUrl)

                // 打开该调试开关并设置TAG,不需要就不要加入该行
                // 最后的true表示是否打印内部异常，一般打开方便调试错误
                .debug("EasyHttp", true)

                //如果使用默认的60秒,以下三行也不需要设置
                .setReadTimeOut(60 * 1000)
                .setWriteTimeOut(60 * 100)
                .setConnectTimeout(60 * 100)
                //可以全局统一设置超时重连次数,默认为3次,那么最差的情况会请求4次(一次原始请求,三次重连请求),
                //不需要可以设置为0
                //网络不好自动重试3次
                .setRetryCount(0)
                //可以全局统一设置超时重试间隔时间,默认为500ms,不需要可以设置为0
                //每次延时500ms重试
                .setRetryDelay(500)
                //可以全局统一设置超时重试间隔叠加时间,默认为0ms不叠加
                //每次延时叠加500ms
                .setRetryIncreaseDelay(500)
                //可以全局统一设置缓存模式,默认是不使用缓存,可以不传,具体请看CacheMode
                .setCacheMode(CacheMode.NO_CACHE)
                //可以全局统一设置缓存时间,默认永不过期
                //-1表示永久缓存,单位:秒 ，Okhttp和自定义RxCache缓存都起作用
                .setCacheTime(-1)
                //全局设置自定义缓存保存转换器，主要针对自定义RxCache缓存
                //默认缓存使用序列化转化
                .setCacheDiskConverter(new SerializableDiskConverter())
                //全局设置自定义缓存大小，默认50M
                //设置缓存大小为100M
                .setCacheMaxSize(100 * 1024 * 1024)
                //设置缓存版本，如果缓存有变化，修改版本后，缓存就不会被加载。特别是用于版本重大升级时缓存不能使用的情况
                //缓存版本为1
                .setCacheVersion(1)
                //.setHttpCache(new Cache())//设置Okhttp缓存，在缓存模式为DEFAULT才起作用

                //可以设置https的证书,以下几种方案根据需要自己设置
                .setCertificates();                           //方法一：信任所有证书,不安全有风险
    }

    /**
     * 初始化配置信息
     */
    private void inintConfigData() {
        AppConfigUtil appconfig = AppConfigUtil.getInstance();
        appconfig.setConValue(AppConfigConstant.COUPON_SEX, "1");
        appconfig.setConValue(AppConfigConstant.GLOBAL_VIDEO, 0);
        appconfig.setConValue(AppConfigConstant.GLOBAL_COMMON, 0);
        appconfig.setConValue(AppConfigConstant.BANNER_NUM, 3);
        appconfig.setConValue(AppConfigConstant.GLOBAL_STYLE, false);
        appconfig.setConValue(AppConfigConstant.APP_COLOR, "");
        appconfig.setConValue(AppConfigConstant.COUPON_SEX, "");
        appconfig.setConValue(AppConfigConstant.LOGIN_TOKEN, "");
        appconfig.setConValue(AppConfigConstant.NICK_NAME, "");
        appconfig.setConValue(AppConfigConstant.USER_NAME, "");
        appconfig.setConValue(AppConfigConstant.HEAD_ICON, "");
        appconfig.setConValue(AppConfigConstant.EMAIL, "");
        appconfig.setConValue(AppConfigConstant.CODE, "");
        appconfig.setConValue(AppConfigConstant.INVITE_CODE, "");
        appconfig.setConValue(AppConfigConstant.SEX, "");
        appconfig.setConValue(AppConfigConstant.PHONE_NUM, "");
        appconfig.setConValue(AppConfigConstant.MIN_PLAY, 0);
        appconfig.setConValue(AppConfigConstant.INTEGRAL_SWITCH, "0");
        appconfig.setConValue(AppConfigConstant.OTHER_ADV, "");
        appconfig.setConValue(AppConfigConstant.HTTP_CODE_URL, "");
        appconfig.setConValue(AppConfigConstant.COMMENT_RULE, "0");
        List<NewsStyleBean> li = new ArrayList<>();
        appconfig.setConValue(AppConfigConstant.STYLE_BEAN_LIST, li);
        appconfig.setConValue(AppConfigConstant.COMMENT_NUM, "");
        appconfig.setConValue(AppConfigConstant.SECTION_BANNER_NUM, "");
        appconfig.setConValue(AppConfigConstant.LIST_ADV, "0");
        appconfig.setConValue(AppConfigConstant.HOMEADV, "0");
        appconfig.setConValue(AppConfigConstant.COUPONADV, "0");
        appconfig.setConValue(AppConfigConstant.SPECIAL_ID, "0");
        appconfig.setConValue(AppConfigConstant.APP_NAME, "");
        appconfig.setConValue(AppConfigConstant.VERSION_BEAN, new VersionBean.DataBean());
        appconfig.setConValue(AppConfigConstant.ADVURL, "");
        appconfig.setConValue(AppConfigConstant.MINLIKE, "");
        appconfig.setConValue(AppConfigConstant.IP, "");
        List<MessageDetailBean> top = new ArrayList<>();
        appconfig.setConValue(AppConfigConstant.TOPMESSAGE, top);
        appconfig.setConValue(AppConfigConstant.COUNTRYSIDEID, "");
        appconfig.setConValue(AppConfigConstant.AFFAIRSID, "");
        appconfig.setConValue(AppConfigConstant.SPECIALID, "");
        appconfig.setConValue(AppConfigConstant.SECTIONID, "");
        appconfig.setConValue(AppConfigConstant.LINK_URL_SHARE, 0);
    }


    /**
     * NotificationChannel 通道设置
     */
    private void createNotificationChannel(Application baseApplication) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationManager mNotificationManager = (NotificationManager) baseApplication.getSystemService(Context.NOTIFICATION_SERVICE);
            // 通知渠道的id
            String id = CommonUtils.getInstance().getSite() + "";
            // 用户可以看到的通知渠道的名字.
            CharSequence name = baseApplication.getResources().getString(R.string.app_name);

            // 用户可以看到的通知渠道的描述
            String description = baseApplication.getResources().getString(R.string.app_name);
            int importance = NotificationManager.IMPORTANCE_HIGH;
            NotificationChannel mChannel = new NotificationChannel(id, name, importance);
            // 配置通知渠道的属性
            mChannel.setDescription(description);
            // 设置通知出现时的闪灯（如果 android 设备支持的话）
            mChannel.enableLights(true);
            mChannel.setLightColor(Color.RED);
            // 设置通知出现时的震动（如果 android 设备支持的话）
            mChannel.enableVibration(true);
            mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
            //最后在notificationmanager中创建该通知渠道
            mNotificationManager.createNotificationChannel(mChannel);
        }
    }


    @Override
    public void initModuleData(Application application) {
        //阿里推送
        PushServiceFactory.init(application.getApplicationContext());

        createNotificationChannel(application);

        if (!SpfManager.getInstance(application).getBoolean("privacy", true)) {
            // 注册方法会自动判断是否支持小米系统推送，如不支持会跳过注册。
            MiPushRegister.register(application, CommonUtils.getInstance().getXiaoMiId(), CommonUtils.getInstance().getXiaoMiKey());

            // 注册方法会自动判断是否支持华为系统推送，如不支持会跳过注册。
            HuaWeiRegister.register(application);

            // VIVO通道注册
            VivoRegister.register(application);

            String oppoAppkey = CommonUtils.getInstance().getOppoAppKey();
            String oppoAppSecret = CommonUtils.getInstance().getOppoAppSecret();
            // OPPO通道注册
            OppoRegister.register(application, oppoAppkey, oppoAppSecret);
            registerPush(application);

        }

        inintConfigData();
        initHttp(BaseUrl.BASE_URL);
        initLeanCloud(application);
        intBugly(application);

        //分享初始化
        UMConfigure.preInit(application, CommonUtils.getInstance().getUMAppKey(), CommonUtils.getInstance().getUMChannelId());
        //友盟分享初始化设置
        PlatformConfig.setWeixin(CommonUtils.getInstance().getSHARE_WEIXIN_APPID(), CommonUtils.getInstance().getSHARE_WEIXIN_APPSECRET());
        PlatformConfig.setQQZone(CommonUtils.getInstance().getSHARE_QQ_APPID(), CommonUtils.getInstance().getSHARE_QQ_APPSECRET());
        if (!SpfManager.getInstance(application).getBoolean("privacy", true)) {
            UMConfigure.init(application, CommonUtils.getInstance().getUMAppKey(), CommonUtils.getInstance().getUMChannelId(), UMConfigure.DEVICE_TYPE_PHONE, "");
        }

        if (!SpfManager.getInstance(application).getBoolean("privacy", true)) {
            if (CommonUtils.getInstance().getSite() == 148 || CommonUtils.getInstance().getSite() == 145) {
                try {
                    initStatistics();
                } catch (Exception e) {
                    Log.e("initStatistics", e.toString() + "");
                }

            }
        }
    }

    /**
     * 建立推送通道
     */
    public void registerPush(Application application) {
        CloudPushService pushService = PushServiceFactory.getCloudPushService();
        pushService.register(application, new CommonCallback() {
            @Override
            public void onSuccess(String response) {
                Log.d(TAG, "init cloudchannel success");
                PushTools.BindTag("Message_" + CommonUtils.getInstance().getSite());
                PushTools.BindTag("Messagge_0");
                Log.i("@@@@@@@", pushService.getDeviceId());
            }

            @Override
            public void onFailed(String errorCode, String errorMessage) {
                Log.d(TAG, "init cloudchannel failed -- errorcode:" + errorCode + " -- errorMessage:" + errorMessage);
            }
        });

    }

    /**
     * 初始化Bugly
     */
    private void intBugly(Application application) {
        Bugly.init(application.getApplicationContext(), "3e3a8f29d9", false);
        Bugly.setAppChannel(application.getApplicationContext(), application.getResources().getString(R.string.app_name));
    }


}
